//
//  ZMYThemeCommentTableViewController.m
//  奇阅
//
//  Created by 奇阅科技 on 14-11-11.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ZMYThemeCommentTableViewController.h"
#import "ZMYThemeCommentHeadTableViewCell.h"
#import "ZMYThemeCommentTableViewCell.h"
#import "TextInputView.h"
#import "Config.h"
#import "UIScrollView+VORefresh.h"
@interface ZMYThemeCommentTableViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    
//    __weak IBOutlet UIView *flaseInputView;
    TextInputView *inputView;
    
    BOOL isHasMore;
}
@property(nonatomic,strong)NSMutableArray *commentArray;
@property(nonatomic,strong)ReplyComment *replyComment;
@end

@implementation ZMYThemeCommentTableViewController
-(void)dealloc{
    NSLog(@"书评回复页释放了");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = NO;
    [self setBarBackgroundImage:@"navBackground"];
    [self setLeftBackButtonForNavigation];
    [self.tableView addTopRefreshWithTarget:self action:@selector(getNetNewDataArray)];
    [self.tableView addBottomRefreshWithTarget:self action:@selector(getMoreDataArray)];
    [self getNetNewDataArray];
    __weak typeof(self) weakSelf = self;
    inputView = [[TextInputView alloc]initWithTitle:@"写书评" textString:^(NSString *textString) {
        ReplyComment *comment = [ReplyComment new];
        UserAccount *user = [UserAccount currentAccount];
        comment.uid = user.uid;
        comment.time = [NSString stringWithFormat:@"%.f",[ZMYNetWorkAPI currentTime]];
        comment.nickName = user.nickname.length>1?user.nickname:user.username;
        comment.headimg = user.headimg;
        comment.commentid = weakSelf.themeComment.commentid;
        BOOL isReply = [textString hasPrefix:@"回复"];
        if (isReply) {
            if (weakSelf.replyComment) {
                comment.contents = [textString substringFromIndex:[NSString stringWithFormat:@"回复 %@:",weakSelf.replyComment.nickName].length];
                comment.replyCommentsid = weakSelf.replyComment.commentsid;
                comment.replyNickName = weakSelf.replyComment.nickName;
            } else {
                weakSelf.replyComment = nil;
                comment.contents = textString;
            }
        } else {
            weakSelf.replyComment = nil;
            comment.contents = textString;
        }
        if (weakSelf.commentArray) {
            [weakSelf.commentArray insertObject:comment atIndex:0];
        } else {
            weakSelf.commentArray = [NSMutableArray arrayWithObject:comment];
        }
        
        [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        [weakSelf.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationRight];
        [weakSelf.navigationController setSGProgressPercentage:1 andTintColor:YellowColor];
        [[ZMYNetWorkAPI default]commentWithArticleid:weakSelf.themeComment.book ThemeComment:weakSelf.themeComment ReplyComment:weakSelf.replyComment content:comment.contents response:^(NSDictionary *resultDic) {
            comment.commentsid = [resultDic objectForKey:@"commentsid"];
            [[ZMYLKDB getLKDBHelper]updateReplyComment:comment];
            [weakSelf.navigationController setSGProgressPercentage:100 andTintColor:YellowColor];
        } progress:^(CGFloat progres) {
            [weakSelf.navigationController setSGProgressPercentage:progres*100 andTintColor:YellowColor];
        } error:^(NSString *errorStr) {
            [weakSelf.navigationController cancelSGProgress];
        }];
    }];
}
//-(void)initData{
//    self.commentArray = [NSMutableArray arrayWithArray:[[ZMYLKDB getLKDBHelper]getReplyCommentWith:self.themeComment]];
//    [self getNetNewDataArray];
//}
-(void)getNetNewDataArray{
    [self.navigationController setSGProgressPercentage:80 andTintColor:YellowColor];
    [[ZMYNetWorkAPI default]getReplyCommentWithThemeComment:self.themeComment pageCommentsId:@"0" Response:^(NSDictionary *resultDict) {
        [self.navigationController setSGProgressPercentage:100];
        self.themeComment = [resultDict objectForKey:@"theme_comments"];
        self.commentArray = [NSMutableArray arrayWithArray:[[ZMYLKDB getLKDBHelper]getReplyCommentWith:self.themeComment]];
        NSInteger count = [[resultDict objectForKey:@"count"] integerValue];
        if (self.commentArray.count<count) {
            isHasMore = YES;
        } else {
            isHasMore = NO;
            [self.tableView removeBottomRefresh];
        }
        [self.tableView reloadData];
        [self.tableView.topRefresh endRefreshing];
    } error:^(NSString *errorStr) {
        [self.tableView.topRefresh endRefreshing];
        [self.navigationController cancelSGProgress];
    }];
}
-(void)getMoreDataArray{
    if (isHasMore) {
        ReplyComment *comment = self.commentArray.lastObject;
        [[ZMYNetWorkAPI default]getReplyCommentWithThemeComment:self.themeComment pageCommentsId:comment.commentsid Response:^(NSDictionary *resultDict) {
            [self.tableView.bottomRefresh endRefreshing];
            [self.commentArray addObjectsFromArray:[resultDict objectForKey:@"commentsList"]];
            NSInteger count = [[resultDict objectForKey:@"count"] integerValue];
            if (self.commentArray.count<count) {
                isHasMore = YES;
            } else {
                isHasMore = NO;
                [self.tableView removeBottomRefresh];
            }
            [self.tableView reloadData];
        } error:^(NSString *errorStr) {
            [self.tableView.bottomRefresh endRefreshing];
            [AppDelegate showHUDAndHide:errorStr view:self.view];
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return self.commentArray.count;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        CGSize commSize = [self.themeComment.contents boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-16, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil].size;
        return commSize.height+105;
    }
    ReplyComment *comment = self.commentArray[indexPath.row];
    CGSize commSize = [comment.contents boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-16, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil].size;
    return commSize.height+65;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZMYThemeCommentHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZMYThemeCommentHeadTableViewCell" forIndexPath:indexPath];
        [cell.headImageView setImageWithURL:[NSURL URLWithString:self.themeComment.headimg]placeholderImage:[UIImage imageNamed:@"touxiang"]];
        cell.nickNameLabel.text = self.themeComment.nickName;
        cell.timeLabel.text = [NSString intDateToStrFromNSTimeInterval:self.themeComment.time];
        cell.commentLabel.text = self.themeComment.contents;
        cell.praiseNumLabel.text = self.themeComment.point_like;
        cell.commentNumLabel.text = self.themeComment.reply_num;
        LikeComment *like = [LikeComment new];
        like.articleid = self.themeComment.articleid;
        like.commentid = self.themeComment.commentid;
        UserAccount *user = [UserAccount currentAccount];
        if (!user) {
            like.uid = @"love";
        } else {
            like.uid = user.uid;
        }
        if ([[ZMYLKDB getLKDBHelper]getIsLike:like]) {
            cell.likeImageView.image = [UIImage imageNamed:@"mypraise"];
            cell.praiseNumLabel.textColor = [UIColor whiteColor];
        } else {
            cell.likeImageView.image = [UIImage imageNamed:@"mynopraise"];
            cell.praiseNumLabel.textColor = RGB_COLOR(160, 160, 160);
        }
        cell.comment = self.themeComment;
        return cell;
    } else {
        ReplyComment *comment = self.commentArray[indexPath.row];
        ZMYThemeCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZMYThemeCommentTableViewCell" forIndexPath:indexPath];
        [cell.headImageView setImageWithURL:[NSURL URLWithString:comment.headimg]placeholderImage:[UIImage imageNamed:@"touxiang"]];
        cell.nickNameLabel.text = comment.nickName;
        cell.timeLabel.text = [NSString intDateToStrFromNSTimeInterval:comment.time];
        cell.commentLabel.text = comment.contents;
        if (comment.replyNickName) {
            cell.replyLabel.hidden = NO;
            cell.replyNickNameLabel.hidden = NO;
            cell.replyNickNameLabel.text = comment.replyNickName;
        } else {
            cell.replyLabel.hidden = YES;
            cell.replyNickNameLabel.hidden = YES;
        }
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        inputView.commentTextView.text = @"";
        self.replyComment = nil;
        [inputView showInputView];
    } else {
        ReplyComment *comment = self.commentArray[indexPath.row];
        inputView.commentTextView.text = [NSString stringWithFormat:@"回复 %@:",comment.nickName];
        self.replyComment = comment;
        [inputView showInputView];
    }
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)inputCommentClick:(id)sender {
    [inputView showInputView];
}
@end
